﻿using Acme.SmartWMS.BasicInfo.IClassificationService;
using Acme.SmartWMS.BasicInfo.IClassificationService.DTO;
using Acme.SmartWMS.Common;
using Acme.SmartWMS.DataBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Acme.SmartWMS.BasicInfo
{
    public class ClassificationAppService:ApplicationService, IClassificationAppService
    {
        private readonly IRepository<DictItem> _itemRepository;

        public ClassificationAppService(IRepository<DictItem> itemRepository)
        {
            _itemRepository = itemRepository;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task<int> Add(DictItemInsertDTO itemdto)
        {
            DictItem dictItem = await _itemRepository.InsertAsync(itemdto.MapTo<DictItem>());
            return dictItem == null ? 0 : 1;
        }

        /// <summary>
        /// 查询显示
        /// </summary>
        /// <param name="name"></param>
        /// <param name="limit"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public async Task<PagedResult<DictItem>> GetDictItem(string? name,int limit,int page)
        {
            PagedResult<DictItem> result = new PagedResult<DictItem>();
            var items = (await _itemRepository.GetListAsync(x => x.DictTypeId == 3&&(string.IsNullOrEmpty(name) || x.DictItemName.Contains(name)))).AsQueryable();
            result.RowCount = items.Count();
            result.PageCount = (int)Math.Ceiling(items.Count() *1.0 / limit);
            result.Queryable = items.Skip((page - 1)* limit).Take(limit).AsQueryable();
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> Del(int id)
        {
            await _itemRepository.DeleteAsync(x=>x.Id == id);
            return 1;
        }

        /// <summary>
        /// 查询单个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<DictItemSelDTO> SelSing(int id)
        {
            DictItemSelDTO selDTO = (await _itemRepository.FirstOrDefaultAsync(x=>x.Id == id)).MapTo<DictItemSelDTO>();
            return selDTO;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="itemdto"></param>
        /// <returns></returns>
        public async Task<int> Upd(DictItemUpdateDTO itemdto)
        {
            DictItem dictItem = await _itemRepository.UpdateAsync(itemdto.MapTo<DictItem>());
            return dictItem == null ? 0 : 1;
        }
    }
}
